package com.dai.zhenfujin.visitingcard;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.dai.zhenfujin.Constants.Constants;
import com.dai.zhenfujin.R;
import com.dai.zhenfujin.base.BaseActivity;
import com.dai.zhenfujin.bean.ProListBean;
import com.dai.zhenfujin.http.CallBack;
import com.dai.zhenfujin.http.HttpClient;
import com.dai.zhenfujin.utils.SPUtils;
import com.dai.zhenfujin.utils.UIUtils;
import com.dai.zhenfujin.visitingcard.adapter.VisitingCardAdapter2;
import com.dai.zhenfujin.visitingcard.app.ParticularsPageActivity;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SearchActiviy extends BaseActivity {

    private FrameLayout fl_img;
    private TextView title_textview;
    private EditText message_search,query;
    private ListView listView;
    private VisitingCardAdapter2 adapter;
    private List<ProListBean.ProListBean2> proListBBean = new ArrayList<>();
    private int page = 1;
    private int number = 10;
    private SmartRefreshLayout refreshLayout;
    protected ImageButton clearSearch;
    protected InputMethodManager inputMethodManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.search_activity);
        inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
        initView();
        onRefresh();
       // initRefresh();
    }

    private void initRefresh() {
        page = 1;
        getProList(true);
    }

    private void onRefresh() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(final RefreshLayout refreshLayout) {
                refreshLayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        page = 1;
                        getProList(true);
                        refreshLayout.finishRefresh();
                        refreshLayout.resetNoMoreData();
                    }
                },1500);
            }
        });

        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getProList(false);
            }
        });
    }

    private void initView() {
        fl_img = findViewById(R.id.fl_img);
        title_textview = findViewById(R.id.title_textview);
        message_search = findViewById(R.id.message_search);
        listView = findViewById(R.id.list);
        refreshLayout = findViewById(com.dai.zhenfujin.R.id.refreshLayout);
        query = findViewById(R.id.query);
        clearSearch = findViewById(R.id.search_clear);

        title_textview.setText("搜索");
        fl_img.setOnClickListener(v -> finish());

        adapter = new VisitingCardAdapter2(this, proListBBean);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener((parent, view, position, id) -> {
                Intent intent = new Intent(this, ParticularsPageActivity.class);
                intent.putExtra("pro_id", proListBBean.get(position).getPro_id());
                intent.putExtra("type_id", proListBBean.get(position).type_id);
                startActivity(intent);
        });

        query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //点击搜索的时候隐藏软键盘
                    //  hideKeyboard(EditText);
                    // 在这里写搜索的操作,一般都是网络请求数据
                    message_search.setText(v.getText().toString().trim());
                    page = 1;
                    getProList(true);
                    return true;
                }

                return false;
            }
        });

        query.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() > 0) {
                    clearSearch.setVisibility(View.VISIBLE);
                } else {
                    clearSearch.setVisibility(View.INVISIBLE);
                    message_search.setText("");
                    proListBBean.clear();
                    adapter.notifyDataSetChanged();
                   // page = 1;
                  //  getProList(true);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        clearSearch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                query.getText().clear();
                hideSoftKeyboard();
            }
        });
    }

    private void hideSoftKeyboard() {
        if (getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (getCurrentFocus() != null)
                inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void getProList(boolean isRefresh) {
        Map<String, Object> params = new HashMap<>();
        Map<String, String> params2 = new HashMap<>();
        params2.put("type_id", 0 + "");
        params2.put("words", message_search.getText().toString().trim());
        params2.put("page", page + "");
        params2.put("number", number + "");
        params2.put("loc_x", SPUtils.getString(this,"longitude"));
        params2.put("loc_y",  SPUtils.getString(this,"latitude"));
        params.put("req_bd", params2);
        HttpClient.post(this, Constants.PRODUCTLIST, params, new CallBack<ProListBean>() {
            @Override
            public void onSuccess(ProListBean proListBean) {
                if (isRefresh) {
                    proListBBean.clear();
                    page = 2;
                } else {
                    page++;
                    refreshLayout.finishLoadmore();
                }
                if (proListBean.getProList().size() > 0) {
                    proListBBean.addAll(proListBean.getProList());
                    adapter.notifyDataSetChanged();
                } else {
                    refreshLayout.finishLoadmoreWithNoMoreData();//将不会再次触发加载更多事件
                }
            }
        });
    }
}
